import {
    list,
    find
  } from '../../../api/product';
  import {
    list as addressList
  } from '../../../api/address.js';
  import {
    add,
    exists,
    del
  } from '../../../api/memberFavorites.js'
  import {
    add as traceAdd
  } from '../../../api/trace.js'
  import {
    IPLocation
  } from '../../../api/amap.js'
  import {
    freight
  } from '../../../api/freight.js'
  import {
    reviewList
  } from '../../../api/review.js'

  import {
    lockSysUser, createQrcode
  } from '../../../api/member'

  const util = require('../../../utils/util.js')
  import css2canvas from "../../../utils/css2canvas"
  let app = getApp();
  Page({

    data: {
      obj:{},
      background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
      swiperImg: [],
      swiperVideo: [],
      product: '',
      current: '1',
      // nav: ['商品', '评价', '详情'],
      nav: ['商品','详情'],
      hiddenNav: true,
      navId: '0',
      couponType: false,
      addressType: false,
      id: '',
      content: '',
      pageNum: 0,
      pageSize: 10,
      productList: [],
      address: {
        areaName: '福建省',
        address: '厦门市',
        areaId: 1166
      },
      swiperIndex: 0,
      addressInfo: [],
      spec: '选择规格',
      freight: null,
      activity: [],
      secondsKill: [],
      couple: [],
      secondThing: [],
      point:[],
      priceBox: [],
      hoursData: '00',
      minutesData: '00',
      secondsData: '00',
      timer: null,
      commentsData: [],
      circular: true,
      existsType: 0,
      noMail: [],
      promotions: [],
      haveInvaild: false,
      cardInfo: {
        TagText: "****", //标签
        Name: '****', //姓名
        avater: "", //需要https图片路径
        qrCode: "", //需要https图片路径
        price: '**',
        logo: 'http://cdnx.rzico.com/images/canvasMyLogo.png',
        coupons:'',
        marketPrice:'',
        activityPrice:''
      },
      history: 0,
      canvasHeight: 400,
      canvasH: 0,
      canvasType: false,
      qrcode: '',
      carvasAvater:'',
      carvasQrCode:'',
      carvasLogo:'',
      stockBox:0,
      shareType:false,
      canvasBottonTitle:'保存图片至相册',
      platform:app.globalData.platform
    },
    onUnload: function () {
      clearInterval(this.data.timer)
    },
    startLockSysUser() {
      lockSysUser({ mchId: app.globalData.mchId, xuid: app.globalData.xuid }).then(res => {
        console.log(res)
      })
    },
    onLoad: function (options) {
      let obj = JSON.parse(options.obj)
      this.data.obj = obj
      this.setData({
        obj:this.data.obj
      })
      var _this = this;
      _this.data.id = options.id
      app.userInfoReadyCallback = res => {
         util.forwarding(options,app.globalData.token)
      }
      if (app.globalData.loaded == true) {
         util.forwarding(options,app.globalData.token)
      }
      this.freightClick()
      this.findClick()
      this.loadPorduct()
      this.loadReviewList()
      this.existsClick()
      this.data.canvasH = (wx.getSystemInfoSync().windowWidth / 750).toFixed(2)
      this.data.canvasHeight = 650 * this.data.canvasH
      this.setData({
        statusBarHeight: app.globalData.statusBarHeight,
        id: this.data.id,
        height: wx.getSystemInfoSync().windowHeight,
        width: wx.getSystemInfoSync().windowWidth,
        canvasHeight: this.data.canvasHeight
      });
      this.createQrcodeClick()

    },
    groupClick() {
      wx.navigateTo({
          url: '/pages/functions/jumpPage/groupbuy/groupOrder?groupBuyId=' + this.data.obj.groupId,
      })
    },
    invFriendsClick(){
      console.log()
      wx.navigateTo({
        url:`/pages/goods/submit/cluster/cluster?id=`+this.data.obj.groupId,
      })
    },
    onShow() {
      if (app.globalData.token != null) {
        this.loadAddress()
      }
      if (app.globalData.token == null) {
        this.amapClick()
      }
      const {
        userInfo
      } = app.globalData
      if (userInfo) {
        if (userInfo.hasOwnProperty("avatar")) {
          this.data.cardInfo.logo = app.globalData.userInfo.avatar
          this.setData({
            cardInfo: this.data.cardInfo
          })
        }
        if (userInfo.hasOwnProperty("nickname")) {
          this.data.cardInfo.Name = app.globalData.userInfo.nickname
          this.setData({
            cardInfo: this.data.cardInfo
          })
        }
      }

    },
    swiperChange(data) {
      var _this = this
      this.data.current = data.detail.current + 1
      this.setData({
        current: this.data.current
      })
    },
    // 监听滚动事件
    bindscroll(e) {
      let _this = this;
      let query = wx.createSelectorQuery()
      query.select('#anchor1').boundingClientRect()
      query.selectViewport().scrollOffset()
      query.exec(function (res) {
        if (res[0].top > -200 && _this.data.hiddenNav == false) {
          _this.setData({
            hiddenNav: true
          })
        } else if (res[0].top < -190 && _this.data.hiddenNav == true) {
          _this.setData({
            hiddenNav: false
          })
        }
      })
      query.select('#anchor2').boundingClientRect()
      query.select('#anchor3').boundingClientRect()
      query.selectViewport().scrollOffset()
      query.exec(function (res) {
        if (res[2].top < 66 && _this.data.navId != 1 && _this.data.navId != 2) {
          _this.setData({
            navId: 1
          })
        }
        if (res[2].top > 66 && _this.data.navId == 1) {
          _this.setData({
            navId: 0
          })
        }
        if (res[3].top < 66 && _this.data.navId != 2 && _this.data.navId == 1) {
          _this.setData({
            navId: 2
          })
        }
        if (res[3].top > 66 && _this.data.navId == 2) {
          _this.setData({
            navId: 1
          })
        }
      })
    },
    toScroll(e) {
      let index = e.currentTarget.dataset.index
      let mmp = ''
      switch (index) {
        case 0:
          mmp = 'anchor1'
          break;
        case 1:
          mmp = 'anchor2'
          break;
        case 2:
          mmp = 'anchor3'
          break;
        default:
          break
      }
      this.setData({
        toview: mmp
      })
    },
    couponClick() {
      this.data.couponType = true
      this.setData({
        couponType: this.data.couponType
      })
    },
    addressClick() {
      this.data.addressType = true
      this.setData({
        addressType: this.data.addressType
      })
    },
    cancleClick() {
      this.data.couponType = false
      this.setData({
        couponType: this.data.couponType
      })
    },
    cancleAddress() {
      this.data.addressType = false
      this.setData({
        addressType: this.data.addressType
      })
    },
    addressChoose(data) {
      var _this = this
      _this.data.address = data.detail
      this.data.addressType = false
      _this.freightClick()
      _this.setData({
        address: _this.data.address,
        addressType: _this.data.addressType
      })
    },
    commentsClick() {
      wx.navigateTo({
        url: '/pages/goods/product/comments?id=' + this.data.id,
      })
    },
    backClick() {
      wx.navigateBack({
        delta: 1,
        fail: res => {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
      })
    },
    findClick() {
      var _this = this
      _this.data.stockBox = 0
      find(_this.data.id).then(
        res => {
          if (res.type == 'success') {
            _this.data.product = res.data.products[0];
            console.log(res.data.products[0],res.data.products[0].thumbnail)
            if(res.data.products.length > 0){
              res.data.products.forEach(function(item){
                _this.data.stockBox += Number(item.stock)
              })
            }
            if (res.data.products[0].spec != '') {
              _this.data.spec = res.data.products[0].spec
            } else {
              _this.data.spec = '请选择规格'
            }
            if (_this.data.stockBox == 0 || _this.data.product.isMarketable == false) {
              _this.data.haveInvaild = true
            }
            if (!util.isNull(res.data.meta)) {
              if (!util.isNull(res.data.meta.images)) {
                _this.data.swiperImg = res.data.meta.images;
              }
              if (!util.isNull(res.data.meta.video)) {
                _this.data.swiperVideo = res.data.meta.video;
              }
            }
            if (!util.isNull(res.data.content)) {
              const regex = new RegExp('<img', 'gi');
              _this.data.content = res.data.content.replace(regex, `<img style="width: 100%;display:block"`);
            }
            if (_this.data.swiperVideo == '') {
              this.data.swiperIndex = _this.data.swiperImg.length
            } else {
              this.data.swiperIndex = _this.data.swiperImg.length + 1
            }
            _this.traceClick()
            _this.setData({
              point:_this.data.point,
              swiperImg: _this.data.swiperImg,
              swiperVideo: _this.data.swiperVideo,
              product: _this.data.product,
              content: _this.data.content,
              swiperIndex: _this.data.swiperIndex,
              secondsKill: _this.data.secondsKill,
              couple: _this.data.couple,
              secondThing: _this.data.secondThing,
              priceBox: _this.data.priceBox,
              noMail: _this.data.noMail,
              haveInvaild: _this.data.haveInvaild,
              spec: _this.data.spec,
              stockBox:_this.data.stockBox
            })
          }
        }
      )
    },
    showBottomFrame: function (e) {
      this.selectComponent('#bottomFrame').showFrame(this.data.id, "attribute");
    },
    showCarrame: function (e) {
      this.selectComponent('#bottomFrame').showFrame(this.data.id, "addCart");
    },
    submitClick(e){
      this.selectComponent('#bottomFrame').bounceGroup(this.data.id,this.data.obj);
    },
    loadPorduct() {
      var _this = this
      list({
        pageNum: _this.data.pageNum,
        pageSize: _this.data.pageSize,
        mchId: app.globalData.mchId
      }).then(
        res => {
          if (res.type == 'success') {
            res.data.data.forEach(function (item) {
              item.thumbnail = util.thumbnail(item.thumbnail, 350, 360)
            })
            _this.data.productList = res.data.data
            _this.setData({
              productList: _this.data.productList
            })
          }
        }
      ).catch(error => {
        console.log(error)
      })
    },
    loadAddress() {
      var _this = this
      addressList({
        mchId: app.globalData.mchId
      }).then(res => {
        _this.data.addressInfo = res.data.data
        if (res.data.data.length > 0) {
          _this.data.address = res.data.data[0]
          _this.freightClick()
          _this.setData({
            address: _this.data.address
          })
        } else {
          _this.amapClick()
        }
        _this.setData({
          addressInfo: _this.data.addressInfo
        })
      }).catch(error => {
        console.log(error)
      })
    },
    selectedInfo(data) {
      var _this = this
      console.log(data)
      _this.data.priceBox = data.detail.price;
      _this.data.spec = data.detail.spec;
      _this.data.id = data.detail.productId
      _this.setData({
        priceBox: _this.data.priceBox,
        spec: _this.data.spec,
        id: _this.data.id
      })
    },
    favoritesClick() {
      var _this = this
      if (_this.data.existsType == 0) {
        var memberFavorites = {
          productId: _this.data.product.id,
          productType: 0
        }
        add(memberFavorites).then(res => {
          if (res.type == 'success') {
            wx.showToast({
              title: "收藏成功"
            })
            _this.existsClick()
          }
        }).catch(error => {
          wx.showToast({
                  icon: "none",
            title: error.content,
          })
        })
      } else {
        del(_this.data.id).then(res => {
          console.log(res)
          if (res.type == 'success') {
            wx.showToast({
              title: "取消收藏",
              icon: "none"
            })
            _this.existsClick()
          }
        }).catch(error => {
          wx.showToast({
                  icon: "none",
            title: error.content,
          })
        })
      }
    },
    traceClick() {
      var _this = this
      var memberTrace = {
        productId: _this.data.product.id,
        productType: 0
      }
      traceAdd(memberTrace).then(res => {
        console.log(res)

      }).catch(error => {

      })
    },
    indexClick() {
      wx.switchTab({
        url: '/pages/index/index',
      })
    },
    amapClick() {
      var _this = this
      IPLocation().then(res => {
        if (res.type == 'success') {
          _this.data.address.address = res.data.address
          _this.data.address.areaName = res.data.name
          _this.data.address.areaId = res.data.areaId
          _this.freightClick()
          _this.setData({
            address: _this.data.address
          })
        } else {
          _this.freightClick()
        }
      }).catch(error => {
        _this.freightClick()
      })
    },
    freightClick() {
      var _this = this
      freight({
        areaId: _this.data.address.areaId,
        productId: _this.data.id
      }).then(res => {
        if (res.type == 'success') {
          _this.data.freight = res.data
          _this.setData({
            freight: _this.data.freight
          })
        } else {
          console.log(res.content)
        }
      }).catch(error => {
        console.log(error.content)
      })
    },
    // 倒计时
    timeFun() {
      var _this = this;
      if (_this.data.activity[0].type == '8') {
        var leftTime = (new Date(_this.data.activity[0].endDate)) - (new Date()); //计算剩余的毫秒数
        var date = new Date(leftTime)
        var hours = date.getHours();
        if (hours > 0) {
          hours = (hours < 10 ? ('0' + hours) : hours) - 8;
        } else {
          hours = 0
        }
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        minutes = minutes < 10 ? ('0' + minutes) : minutes;
        seconds = seconds < 10 ? ('0' + seconds) : seconds;
        var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
        _this.data.hoursData = hours + (days * 24);
        _this.data.minutesData = minutes;
        _this.data.secondsData = seconds;
        _this.setData({
          hoursData: _this.data.hoursData,
          minutesData: _this.data.minutesData,
          secondsData: _this.data.secondsData
        })
      }
    },
    // 释放定时器
    countdownBox() {
      var _this = this
      if (this.data.timer != null) {
        clearInterval(this.data.timer);
        this.data.timer = null;
      }
      this.data.timer = setInterval(function () {
        _this.timeFun()
      }, 1000)
    },
    loadReviewList() {
      var _this = this
      reviewList({
        productId: _this.data.id
      }).then(res => {
        console.log(res)
        if (res.type == 'success') {
          _this.data.commentsData = res.data.data
          _this.setData({
            commentsData: _this.data.commentsData
          })
        }
      }).catch(error => {
        wx.showToast({
                icon: "none",
          title: error.content,
        })
      })
    },
    existsClick() {
      var _this = this
      exists({
        productId: _this.data.id
      }).then(res => {
        console.log(res)
        if (res.type == 'success') {
          _this.data.existsType = res.data
          _this.setData({
            existsType: _this.data.existsType
          })
        }
      }).catch(error => {
        wx.showToast({
                icon: "none",
          title: error.content,
        })
      })
    },
    onShareAppMessage: function () {
      console.log(this.data.product.thumbnail + '?x-oss-process=image/resize,m_fixed,h_400,w_500')
      return {
        title: this.data.product.name,
        desc: '为您挑选了一个好物',
        imageUrl: this.data.product.thumbnail + '?x-oss-process=image/resize,m_fixed,h_400,w_500',
        path: '/pages/goods/product/groupBuydetails?id=' + this.data.id + '&xuid=' + app.globalData.userInfo.id+'&obj='+ JSON.stringify(this.data.obj)
      }

    },
    onShareTimeline: function () {
      return {
        title: this.data.product.name,
        desc: '为您挑选了一个好物',
        path: '/pages/goods/product/groupBuydetails?id=' + this.data.id + '&xuid=' + app.globalData.userInfo.id+'&obj='+ JSON.stringify(this.data.obj),
        imageUrl: this.data.product.thumbnail
      }
    },
    sharePosteCanvas: function () {
      var _this = this
      wx.showLoading({
          title: '生成中...',
          mask: true,
      })
      console.log( _this.data.cardInfo.coupons)
      var canvasShow = wx.createCanvasContext("canvas-show")
      let ctx = new css2canvas(canvasShow)
      var canvasForm = [
        {
          type: "roundRect",
          x: 0,
          y: 0,
          width: 550,
          height: 680 ,
          background: "#ffffff",
          borderWidth: 1,
          borderRadius: 0,
          clip: false
        },
        //  {
        //   type: "image",
        //   imgUrl:_this.data.carvasLogo,
        //   x: 20,
        //   y: 20,
        //   width: 60,
        //   height: 60,
        //   borderRadius: 30
        // },
      //   {
      //     type: "text",
      //     x: 90,
      //     y: 20,
      //     color: "black",
      //     fontSize: 28,
      //     baseline: "top",
      //     content: _this.data.cardInfo.Name
      // },
      // {
      //   type: "text",
      //   x: 20,
      //   y: 56,
      //   color: "black",
      //   fontSize: 28,
      //   baseline: "top",
      //   content: _this.data.cardInfo.Name 
      // },
        {
            type: "text",
            x: 20,
            y: 20,
            color: "#999999",
            fontSize: 22,
            baseline: "top",
            content: "为你挑选了一个好物"
        },
         {
          type: "image",
          imgUrl:_this.data.carvasAvater,
          x: 20,
          y: 56,
          width: 398,
          height: 398
        },
        {
          type: "prefixText",
          x: 20,
          y: 505,
          color: "#FF3131",
          textAlign: "left",
          content: _this.data.cardInfo.price,
          tag: "￥",
          fontSize: 36,
          tagSize: 28
        },
        {
          type: "text",
          x: 20,
          y: 515,
          width: 320,
          content: _this.data.cardInfo.TagText,
          color: "#666666",
          fontSize: 24,
          textAlign: "left",
          overflow: "warp",
          maxLine: 1,
          lineHeight: 1
        },
        {
          type: "image",
          imgUrl: _this.data.carvasQrCode,
          x: 265,
          y: 475,
          width: 158,
          height: 158
        },
      ]
      if(_this.data.cardInfo.coupons !=''){
        var coupon = {
          type: "tag",
          x: 20,
          y: 590,
          content: _this.data.cardInfo.coupons,
          background: "red",
          paddingTop: 2,
          paddingBottom: 4,
          paddingLeft:20,
          paddingRight:20,
          color: "#ffffff",
          fontSize: 22,
          borderRadius: 16
        }
        canvasForm.push(coupon)
      }
      if(_this.data.cardInfo.marketPrice !=''){
        var marketPrice = {
          type: "prefixText",
          x:
            ctx.getWidth({
              text: "100",
              fontSize: 36,
              returnPx: false
            }) +
            74,
          y: 545,
          color: "#999999",
          textAlign: "left",
          content: _this.data.cardInfo.marketPrice,
          tag: "￥",
          fontSize: 28,
          tagSize: 20,
          isDel: true,
          delColor: "#999999"
        }
        canvasForm.push(marketPrice)
      }
      if(_this.data.cardInfo.activityPrice !=''){
        var activityPrice = {
          type: "tag",
          x:
          ctx.getWidth({
            text: "100",
            fontSize: 36,
            returnPx: false
          }) +
          74,
          y: 512,
          content: _this.data.cardInfo.activityPrice,
          background: "rgba(247, 219, 194, 1)",
          paddingTop: 2,
          paddingBottom: 4,
          paddingLeft:20,
          paddingRight:20,
          color: "#ffffff",
          fontSize: 22,
          borderRadius: 16
        }
        canvasForm.push(activityPrice)
      }
      ctx
        .drawingView(canvasForm)
        .then(res => {
          console.log("绘制完成")
          wx.hideLoading();
        })

    },


    canvasClick() {
      var _this = this
      this.data.shareType = false
      this.data.canvasType = true
      this.data.cardInfo.avater = this.data.product.thumbnail
      this.data.cardInfo.TagText = this.data.product.name
      this.data.cardInfo.price = this.data.product.price
      console.log(this.data.product)
      if(this.data.product.coupons.length > 0){
        _this.data.cardInfo.coupons = _this.data.product.coupons[0].name
      }
      if(_this.data.activity.length == 0 && _this.data.product.marketPrice != _this.data.product.price){
        _this.data.cardInfo.marketPrice = _this.data.product.marketPrice
      }
      if (_this.data.activity !=0 && _this.data.activity[0].type =='10'){
        _this.data.cardInfo.activityPrice = '新人价 ¥'+_this.data.activity[0].price
      }
      if (_this.data.activity !=0 && _this.data.activity[0].type =='100'){
        _this.data.cardInfo.activityPrice = 'VIP ¥'+_this.data.activity[0].price
      }

       wx.getImageInfo({
        src: util.proxyImage(app.APP_BASE_API,util.thumbnail(_this.data.product.thumbnail,600,600)), //网络图片路径
        success: res => {
          _this.data.carvasAvater = res.path; //图片临时本地路径
          wx.getImageInfo({
            src: util.proxyImage(app.APP_BASE_API,util.thumbnail(_this.data.cardInfo.logo,200,200)), //网络图片路径
            success: res => {
              console.log(res.path, '商品图')
              _this.data.carvasLogo = res.path; //图片临时本地路径
              console.log(_this.data.cardInfo.qrCode,'111')
              wx.getImageInfo({
                
                src: _this.data.cardInfo.qrCode, //网络图片路径
                success: res => {
                  console.log(res.path, '二维码图')
                  this.data.carvasQrCode = res.path; //图片临时本地路径
                  this.setData({
                    canvasType: this.data.canvasType,
                    cardInfo: this.data.cardInfo,
                    shareType:this.data.shareType
                  })
                  console.log(this.data.cardInfo, '二维码图')
                   setTimeout(function () {
                    _this.sharePosteCanvas()
                  }, 1000)
                },
                fail:res=>{
                  console.log(res)
                }
              })
            }
          })
        }
      })

    },
    saveShareImg: function () {
      var that = this;
      if(this.data.canvasBottonTitle == '去分享到朋友圈'){
        this.cancleCanvasClick()
        return
      }
      wx.showLoading({
        title: '正在保存',
        mask: true,
      })
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'canvas-show',
          success: function (res) {
            wx.hideLoading();
            var tempFilePath = res.tempFilePath;
            wx.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success(res) {
                that.data.canvasBottonTitle = '去分享到朋友圈'
                that.setData({
                  canvasBottonTitle:that.data.canvasBottonTitle
                })
                wx.showModal({
                  content: '图片已保存到相册，赶紧晒一下吧~',
                  showCancel: false,
                  confirmText: '好的',
                  confirmColor: '#333',
                  success: function (res) {
                    if (res.confirm) {
                    }
                  },
                  fail: function (res) { }
                })
              },
              fail: function (res) {
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          }
        });
      }, 1000);
    },
    createQrcodeClick() {
      if (app.globalData.token == null) {
        return;
      }
      createQrcode().then(res => {
        this.data.qrcode = res.content
        this.createImageClick()
      }).catch(error => {
        console.log(error)
      })
    },
    createImageClick() {
      let data =  this.data.qrcode+'?groupBuyIds='+this.data.id +'&obj='+ JSON.stringify(this.data.obj)
      this.data.cardInfo.qrCode = app.APP_BASE_API + '/zxing/createImage?data='+encodeURIComponent(data)
      this.setData({
        cardInfo: this.data.cardInfo
      })
      console.log(this.data.cardInfo.qrCode,'qrCode')
    },
    cancleCanvasClick() {
      this.data.canvasType = false
      this.data.canvasBottonTitle = '保存图片至相册'
      this.setData({
        canvasType: this.data.canvasType,
        canvasBottonTitle:this.data.canvasBottonTitle
      })
    },
    cancelShare(){
      this.data.shareType = !this.data.shareType
      this.setData({
        shareType:this.data.shareType
      })
    },
    starShare(){
      this.data.shareType = !this.data.shareType
      this.setData({
        shareType:this.data.shareType
      })
    }
  })

